package cn.edu.anan.aop;

import cn.edu.anan.config.DbContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * 读数据源切面
 *
 * @author ThinkPad
 * @version 1.0
 * @date 2021/9/21 17:07
 */
@Aspect
@Component
@Slf4j
public class ReadOnlyAspect implements Ordered{

    /**
     * 线程上下文设置读数据源
     * @param pjp
     * @param read
     * @return
     * @throws Throwable
     */
    @Around("@annotation(read)")
    public Object setRead(ProceedingJoinPoint pjp, DataSourceSwitcher read) throws Throwable{
        try{
            DbContextHolder.setDbType(DbContextHolder.READ);
            return pjp.proceed();
        }finally {
            DbContextHolder.clearDbType();
            log.info("清除threadLocal");
        }
    }

    /**
     * 顺序
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
